<?php
/**
 * Copyright (c) 2006, PORTALIER Julien
 * 
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 * 
 * @package    FeatherPHP
 * @subpackage Components
 * @copyright  Copyright (c) 2006, Julien PORTALIER
 * @link       http://feather.portalier.com
 * @license    http://www.opensource.org/licenses/mit-license.php The MIT License
 * 
 * @todo Manual session start.
 */

class SessionComponent
{
	function startup(Controller $controller)
	{
		// has a session already been started?
		$sid = session_id();
		if (!empty($sid))
			return;
		
		// config
		ini_set('session.name', Config::session_cookie);
		ini_set('session.use_only_cookies', '1');
		
		session_set_cookie_params(is_string(Config::session_expire) ? strtotime(Config::session_expire) : Config::session_expire,
			Config::session_path, Config::session_domain);
		
		if (Config::session_auto)
			$this->start();
	}
	
	function start()
	{
		session_start();
		
		// browsers may cache pages, proxies may not
		header('Pragma: ');
		header('Expires: ');
		header('Cache-Control: s-maxage=1, proxy-revalidate');
		
		// session exists?
		if (!empty($_SESSION))
		{
			// is something wrong with session?
			if ($_SESSION['Config.string'] != Config::session_string or $_SESSION['Config.IP'] != $_SERVER["REMOTE_ADDR"]) {
				$_SESSION = array();
			}
		}
		
		// new session?
		if (empty($_SESSION))
		{
			$_SESSION['Config.string'] = Config::session_string;
			$_SESSION['Config.IP'] = $_SERVER["REMOTE_ADDR"];
		}
	}
	
	function write($key, $value)
	{
		$_SESSION[$key] = $value;
	}
	
	function read($key)
	{
		return isset($_SESSION[$key]) ? $_SESSION[$key] : null;
	}
	
	function delete($key)
	{
		unset($_SESSION[$key]);
	}
	
	function check($key)
	{
		return isset($_SESSION[$key]);
	}
	
	function setflash($mesg)
	{
		$_SESSION['Flash.message'] = $mesg;
	}
	
	function flash($fancy=true)
	{
		if (isset($_SESSION['Flash.message']))
		{
			$mesg = $_SESSION['Flash.message'];
			unset($_SESSION['Flash.message']);
			return $fancy ? "<p class=\"message\" id=\"message\">$mesg</p>" : $mesg;
		}
	}
}
?>